//
//  GlobalMethod+Data.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/26.
//

#import "GlobalMethod+Data.h"

// 加前缀
#define EXCHANGE_LOCAL_KEY(key)  (key) = [(key) hasPrefix:LOCAL_KEY_HEAD]?(key):[NSString stringWithFormat:@"%@%@",LOCAL_KEY_HEAD,(key)]

@implementation GlobalMethod (Data)

#pragma mark - 清空本地数据
+ (void)clearUserDefault{
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        if ([key isKindOfClass:[NSString class]] && [key hasPrefix:LOCAL_KEY_HEAD]) {
            [defs removeObjectForKey:key];
        }
    }
    [defs synchronize];
}

#pragma mark - 读写本地数据
// 写 - 有前缀
+ (void)writeStr:(NSString *)strValue forKey:(NSString *)strKey{
    if (isStr(strKey) ) {
        EXCHANGE_LOCAL_KEY(strKey);
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user setObject:strValue  forKey:strKey];
        [user synchronize];
    }
}
// 读 - 有前缀
+ (NSString *)readStrFromUserDefaults:(NSString *)strKey{
    if (isStr(strKey)) {
        EXCHANGE_LOCAL_KEY(strKey);
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * strValue = [user objectForKey:strKey];
        if (strValue != nil && [strValue isKindOfClass:[NSString class]]&& strValue.length>0) {
            return strValue;
        }
    }
    return @"";
}
// 写 - 无前缀
+ (void)writeUnprefixStr:(NSString *)strValue forKey:(NSString *)strKey{
    if (isStr(strKey) ) {
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        [user setObject:strValue  forKey:strKey];
        [user synchronize];
    }
}
// 读 - 无前缀
+ (NSString *)readUnprefixStrFromUserDefaults:(NSString *)strKey{
    if (isStr(strKey)) {
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        NSString * strValue = [user objectForKey:strKey];
        if (strValue != nil && [strValue isKindOfClass:[NSString class]]&& strValue.length>0) {
            return strValue;
        }
    }
    return @"";
}
// bool
+ (void)writeBool:(BOOL)bol local:(NSString *)strKey{
    if (!isStr(strKey)) return;
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user setObject:[NSNumber numberWithBool:bol] forKey:strKey];
    [user synchronize];
}
+ (BOOL)readBoolLocal:(NSString *)strKey{
    if (!isStr(strKey)) return NO;
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSNumber *num = [user objectForKey:strKey];
    if (num == nil) return NO;
    return [num boolValue];
}



#pragma mark - 数据类型转换
// 转换String to dic
+ (NSDictionary *)exchangeStringToDic:(NSString *)str{
    if (!isStr(str)) {
        return [NSDictionary dictionary];
    }
    NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dicReturn = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return dicReturn;
}
// 转换String to ary
+ (NSArray *)exchangeStringToAry:(NSString *)str{
    if (!isStr(str)) {
        return [NSArray array];
    }
    NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSArray * aryReturn = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    return aryReturn;
}
// 转换data to dic
+ (NSDictionary *)exchangeDataToDic:(NSData *)data{
    //NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    if (data == nil || ![data isKindOfClass:[NSData class]]) {
        return nil;
    }
    return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
// 转换 dic to model
+ (id)exchangeDicToModel:(NSDictionary *)dic modelName:(NSString *)strName{
    if (!isStr(strName)) {
        return nil;
    }
    Class class = NSClassFromString(strName);
    if (class == nil) {
        return nil;
    }
    if ([dic isKindOfClass:[NSArray class]]) {
        return [self performSelector:@"modelObjectWithDictionary:" delegate:class object:[(NSArray *)dic lastObject] isHasReturn:true];
    }
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        return [[class alloc]init];
    }
    return [self performSelector:@"modelObjectWithDictionary:" delegate:class object:dic isHasReturn:true];
}
// 转换dic to ary
+ (NSMutableArray *)exchangeDic:(id)response toAryWithModelName:(NSString *)modelName{
    if (response == nil || !isStr(modelName)) {
        return [NSMutableArray array];
    }
    id class = NSClassFromString(modelName);
    if (class == nil) {
        return [NSMutableArray array];
    }
    if (response && [response isKindOfClass:[NSDictionary class]]) {
        if ([class respondsToSelector:@selector(modelObjectWithDictionary:)]) {
            id model = [class performSelector:@selector(modelObjectWithDictionary:) withObject:response];
            return [NSMutableArray arrayWithObject:model];
        }
    }
    if (response && [response isKindOfClass:[NSArray class]]) {
        NSMutableArray * aryReturn = [NSMutableArray array];
        for (NSDictionary * dic in (NSArray *)response) {
            if ([class respondsToSelector:@selector(modelObjectWithDictionary:)]) {
                id model = [class performSelector:@selector(modelObjectWithDictionary:) withObject:dic];
                [aryReturn addObject:model];
            }
        }
        return aryReturn;
    }
    return [NSMutableArray array];
}
+ (NSMutableArray *)exchangeAryModelToAryDic:(NSArray *)response{
    if (!isAry(response)) {
        return [NSMutableArray array];
    }
    NSMutableArray * aryReturn = [NSMutableArray array];
    for (NSObject *subArrayObject in response) {
        if ([subArrayObject respondsToSelector:@selector(dictionaryRepresentation)]) {
            // This class is a model object
            [aryReturn addObject:[subArrayObject performSelector:@selector(dictionaryRepresentation)]];
        } else {
            // Generic object
            [aryReturn addObject:subArrayObject];
        }
    }
    return aryReturn;
}

// 转换json
// 字典或者数组转Json
+ (NSString *)exchangeDicToJson:(id)object{
    if (object == nil) {
        NSLog(@"error json转换错误");
        return @"";
    }
    if ([object isKindOfClass:[NSDictionary class]]||[object isKindOfClass:[NSArray class]]) {
        NSData * dataJson = [NSJSONSerialization dataWithJSONObject:object options:0 error:nil];
        NSString * strJson = [[NSString alloc]initWithData:dataJson encoding:NSUTF8StringEncoding];
        return strJson;
    }
    return @"";
}

// Model数组转换为jsong
+ (NSString *)exchangeModelsToJson:(NSArray *)object{
    if (object == nil) {
        NSLog(@"error json转换错误");
        return @"";
    }
    NSMutableArray * aryMu = [NSMutableArray new];
    if ([object isKindOfClass:[NSArray class]]) {
        for (id model in object) {
            NSDictionary * dic = [GlobalMethod performSelector:@"dictionaryRepresentation" delegate:model object:nil isHasReturn:true];
            if (dic != nil) {
                [aryMu addObject:dic];
            }
        }
    }
    return [self exchangeDicToJson:aryMu];
}

// model转换json
+ (NSString *)exchangeModelToJson:(id)model{
    if (!model) return @"";
    if (![model respondsToSelector:@selector(dictionaryRepresentation)]) return @"";
    NSDictionary * dicJson = [model dictionaryRepresentation];
    NSData * dataJson = [NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];
    NSString * strJson = [[NSString alloc]initWithData:dataJson encoding:NSUTF8StringEncoding];
    return strJson!=nil?strJson:@"";
}

#pragma mark - 日期时间
// date 转 时间戳
+ (NSString *)changeDateToStr:(NSDate *)date{
    NSTimeInterval interval = [date timeIntervalSince1970];
    long long totalMilliseconds = interval*1000 ;
    return [NSString stringWithFormat:@"%llu",totalMilliseconds];
}
// date 转 (formate格式) - NSString
+ (NSString *)exchangeDate:(NSDate *)date formatter:(NSString *)formate{
    if (date == nil || formate == nil) {
        return @"";
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formate];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    return currentDateStr;
}
// NSString 转 (formate格式) - NSDate
+ (NSDate *)exchangeString:(NSString *)str formatter:(NSString *)formate{
    if (str == nil || formate == nil) {
        return [NSDate date];
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formate];
    NSDate *currentDate = [dateFormatter dateFromString:str];
    return currentDate;
}
// 时间戳 转 格式时间
+ (NSString *)exchangeTimestamp:(NSString *)timestampString formate:(NSString *)formate{
    NSTimeInterval timestamp = [timestampString doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: formate];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    return formattedDateString;
}

#pragma mark - double数据显示
+ (NSString *)formattedDouble:(double)number{
    // 创建 NSNumberFormatter 对象
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    // 设置格式为小数形式
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    // 设置最小小数位数为 0，这样整数值将不显示小数部分
    formatter.minimumFractionDigits = 0;
    // 设置最大小数位数为 2，这样小数部分将保留两位小数
    formatter.maximumFractionDigits = 2;
    // 格式化 double 值
    NSString *formattedNumber = [formatter stringFromNumber:@(number)];
    return formattedNumber;
}

@end
